[[...path]].page.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, isServer, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import mongoose from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  17. import { PageComment } from '~/components/PageComment';
  18. // import { useTranslation } from '~/i18n';
  19. import CommentEditorLazyRenderer from '~/components/PageComment/CommentEditorLazyRenderer';
  20. import { CrowiRequest } from '~/interfaces/crowi-request';
  21. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  22. // import { useIndentSize } from '~/stores/editor';
  23. // import { useRendererSettings } from '~/stores/renderer';
  24. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  25. import { CustomWindow } from '~/interfaces/global';
  26. import { RendererConfig } from '~/interfaces/services/renderer';
  27. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  28. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  29. import { PageModel, PageDocument } from '~/server/models/page';
  30. import { PageRedirectModel } from '~/server/models/page-redirect';
  31. import UserUISettings from '~/server/models/user-ui-settings';
  32. import Xss from '~/services/xss';
  33. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  34. import {
  35. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  36. } from '~/stores/ui';
  37. import loggerFactory from '~/utils/logger';
  38. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  39. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  40. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  41. import ForbiddenPage from '../components/ForbiddenPage';
  42. import { BasicLayout } from '../components/Layout/BasicLayout';
  43. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  44. import { NotCreatablePage } from '../components/NotCreatablePage';
  45. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  46. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  47. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  48. import {
  49. useCurrentUser, useCurrentPagePath,
  50. useIsLatestRevision,
  51. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  52. useIsEnabledStaleNotification, useIsIdenticalPath,
  53. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  54. useHackmdUri,
  55. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  56. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  57. useIsSlackConfigured, useIsBlinkedHeaderAtBoot, useRendererConfig, useEditingMarkdown,
  58. } from '../stores/context';
  59. import { useXss } from '../stores/xss';
  60. import {
  61. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  62. } from './utils/commons';
  63. // import { useCurrentPageSWR } from '../stores/page';
  64. const logger = loggerFactory('growi:pages:all');
  65. const {
  66. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage,
  67. } = pagePathUtils;
  68. const { removeHeadingSlash } = pathUtils;
  69. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  70. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  71. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  72. {
  73. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  74. return v?.data != null
  75. && v?.data.toObject != null
  76. && v?.meta != null
  77. && isIPageInfoForEntity(v.meta);
  78. },
  79. serialize: (v) => {
  80. return {
  81. data: superjson.stringify(v.data.toObject()),
  82. meta: superjson.stringify(v.meta),
  83. };
  84. },
  85. deserialize: (v) => {
  86. return {
  87. data: superjson.parse(v.data),
  88. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  89. };
  90. },
  91. },
  92. 'IPageToShowRevisionWithMetaTransformer',
  93. );
  94. const IdenticalPathPage = (): JSX.Element => {
  95. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  96. return <IdenticalPathPage />;
  97. };
  98. const PutbackPageModal = (): JSX.Element => {
  99. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  100. return <PutbackPageModal />;
  101. };
  102. type Props = CommonProps & {
  103. currentUser: IUser,
  104. pageWithMeta: IPageToShowRevisionWithMeta,
  105. // pageUser?: any,
  106. redirectFrom?: string;
  107. // shareLinkId?: string;
  108. isLatestRevision?: boolean
  109. isIdenticalPathPage?: boolean,
  110. isForbidden: boolean,
  111. isNotFound: boolean,
  112. IsNotCreatable: boolean,
  113. // isAbleToDeleteCompletely: boolean,
  114. isSearchServiceConfigured: boolean,
  115. isSearchServiceReachable: boolean,
  116. isSearchScopeChildrenAsDefault: boolean,
  117. isSlackConfigured: boolean,
  118. // isMailerSetup: boolean,
  119. isAclEnabled: boolean,
  120. // hasSlackConfig: boolean,
  121. // drawioUri: string,
  122. hackmdUri: string,
  123. // mathJax: string,
  124. // noCdn: string,
  125. // highlightJsStyle: string,
  126. // isAllReplyShown: boolean,
  127. // editorConfig: any,
  128. isEnabledStaleNotification: boolean,
  129. // isEnabledLinebreaks: boolean,
  130. // isEnabledLinebreaksInComments: boolean,
  131. // adminPreferredIndentSize: number,
  132. // isIndentSizeForced: boolean,
  133. disableLinkSharing: boolean,
  134. rendererConfig: RendererConfig,
  135. // UI
  136. userUISettings?: IUserUISettings
  137. // Sidebar
  138. sidebarConfig: ISidebarConfig,
  139. };
  140. const GrowiPage: NextPage<Props> = (props: Props) => {
  141. // const { t } = useTranslation();
  142. const router = useRouter();
  143. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  144. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  145. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  146. // register global EventEmitter
  147. if (isClient()) {
  148. (window as CustomWindow).globalEmitter = new EventEmitter();
  149. }
  150. // commons
  151. useXss(new Xss());
  152. // useEditorConfig(props.editorConfig);
  153. useCsrfToken(props.csrfToken);
  154. // UserUISettings
  155. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  156. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  157. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  158. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  159. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  160. // page
  161. useCurrentPagePath(props.currentPathname);
  162. useIsLatestRevision(props.isLatestRevision);
  163. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  164. useIsForbidden(props.isForbidden);
  165. useIsNotFound(props.isNotFound);
  166. useIsNotCreatable(props.IsNotCreatable);
  167. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  168. // useShared();
  169. // useShareLinkId(props.shareLinkId);
  170. useIsSharedUser(false); // this page cann't be routed for '/share'
  171. useIsIdenticalPath(false); // TODO: need to initialize from props
  172. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  173. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  174. useIsBlinkedHeaderAtBoot(false);
  175. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  176. useIsSearchServiceReachable(props.isSearchServiceReachable);
  177. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  178. useIsSlackConfigured(props.isSlackConfigured);
  179. // useIsMailerSetup(props.isMailerSetup);
  180. useIsAclEnabled(props.isAclEnabled);
  181. // useHasSlackConfig(props.hasSlackConfig);
  182. // useDrawioUri(props.drawioUri);
  183. useHackmdUri(props.hackmdUri);
  184. // useMathJax(props.mathJax);
  185. // useNoCdn(props.noCdn);
  186. // useIndentSize(props.adminPreferredIndentSize);
  187. useDisableLinkSharing(props.disableLinkSharing);
  188. useRendererConfig(props.rendererConfig);
  189. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  190. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  191. // const { data: editorMode } = useEditorMode();
  192. const { pageWithMeta, userUISettings } = props;
  193. let shouldRenderPutbackPageModal = false;
  194. if (pageWithMeta != null) {
  195. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  196. }
  197. const pageId = pageWithMeta?.data._id;
  198. useCurrentPageId(pageId);
  199. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  200. useSWRxPageInfo(pageId, undefined, pageWithMeta?.meta); // store initial data
  201. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  202. useIsUserPage(isUserPage(pageWithMeta?.data.path ?? ''));
  203. useIsNotCreatable(props.isForbidden || !isCreatablePage(pageWithMeta?.data.path ?? '')); // TODO: need to include props.isIdentical
  204. useCurrentPagePath(pageWithMeta?.data.path);
  205. useCurrentPathname(props.currentPathname);
  206. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  207. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  208. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  209. // sync grant data
  210. useEffect(() => {
  211. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  212. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  213. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  214. useEffect(() => {
  215. const decodedURI = decodeURI(window.location.pathname);
  216. if (isClient() && decodedURI !== props.currentPathname) {
  217. router.replace(props.currentPathname, undefined, { shallow: true });
  218. }
  219. }, [props.currentPathname, router]);
  220. const classNames: string[] = [];
  221. // switch (editorMode) {
  222. // case EditorMode.Editor:
  223. // classNames.push('on-edit', 'builtin-editor');
  224. // break;
  225. // case EditorMode.HackMD:
  226. // classNames.push('on-edit', 'hackmd');
  227. // break;
  228. // }
  229. // if (page == null) {
  230. // classNames.push('not-found-page');
  231. // }
  232. return (
  233. <>
  234. <Head>
  235. {/*
  236. {renderScriptTagByName('drawio-viewer')}
  237. {renderScriptTagByName('mathjax')}
  238. {renderScriptTagByName('highlight-addons')}
  239. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  240. */}
  241. </Head>
  242. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  243. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  244. <header className="py-0">
  245. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  246. </header>
  247. <div className="d-edit-none">
  248. <GrowiSubNavigationSwitcher />
  249. </div>
  250. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  251. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  252. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  253. <div id="content-main" className="content-main grw-container-convertible">
  254. <div className="row">
  255. <div className="col">
  256. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  257. { !props.isIdenticalPathPage && (
  258. <>
  259. <PageAlerts />
  260. { props.isForbidden && <ForbiddenPage /> }
  261. { props.IsNotCreatable && <NotCreatablePage />}
  262. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  263. {/* <DisplaySwitcher /> */}
  264. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  265. {/* <PageStatusAlert /> */}
  266. </>
  267. ) }
  268. </div>
  269. </div>
  270. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  271. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  272. <div id="revision-toc-content" className="revision-toc-content"></div>
  273. </div>
  274. </div> */}
  275. </div>
  276. </div>
  277. <footer>
  278. <PageComment pageId={useCurrentPageId().data} isReadOnly={false} titleAlign="left" />
  279. {/* <CommentEditorLazyRenderer pageId={useCurrentPageId().data} /> */}
  280. </footer>
  281. <UnsavedAlertDialog />
  282. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  283. </BasicLayout>
  284. </>
  285. );
  286. };
  287. function getPageIdFromPathname(currentPathname: string): string | null {
  288. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  289. }
  290. class MultiplePagesHitsError extends ExtensibleCustomError {
  291. pagePath: string;
  292. constructor(pagePath: string) {
  293. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  294. this.pagePath = pagePath;
  295. }
  296. }
  297. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  298. const req: CrowiRequest = context.req as CrowiRequest;
  299. const { crowi } = req;
  300. const { revisionId } = req.query;
  301. const Page = crowi.model('Page') as PageModel;
  302. const PageRedirect = mongoose.model('PageRedirect') as PageRedirectModel;
  303. const { pageService } = crowi;
  304. let currentPathname = props.currentPathname;
  305. const pageId = getPageIdFromPathname(currentPathname);
  306. const isPermalink = _isPermalink(currentPathname);
  307. const { user } = req;
  308. if (!isPermalink) {
  309. // check redirects
  310. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  311. if (chains != null) {
  312. // overwrite currentPathname
  313. currentPathname = chains.end.toPath;
  314. props.currentPathname = currentPathname;
  315. // set redirectFrom
  316. props.redirectFrom = chains.start.fromPath;
  317. }
  318. // check whether the specified page path hits to multiple pages
  319. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  320. if (count > 1) {
  321. throw new MultiplePagesHitsError(currentPathname);
  322. }
  323. }
  324. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  325. const page = pageWithMeta?.data as unknown as PageDocument;
  326. // populate & check if the revision is latest
  327. if (page != null) {
  328. page.initLatestRevisionField(revisionId);
  329. await page.populateDataToShowRevision();
  330. props.isLatestRevision = page.isLatestRevision();
  331. }
  332. props.pageWithMeta = pageWithMeta;
  333. }
  334. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  335. const req = context.req as CrowiRequest<IUserHasId & any>;
  336. const { user } = req;
  337. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  338. if (userUISettings != null) {
  339. props.userUISettings = userUISettings.toObject();
  340. }
  341. }
  342. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  343. const req: CrowiRequest = context.req as CrowiRequest;
  344. const { crowi } = req;
  345. const Page = crowi.model('Page') as PageModel;
  346. const { currentPathname } = props;
  347. const pageId = getPageIdFromPathname(currentPathname);
  348. const isPermalink = _isPermalink(currentPathname);
  349. const page = props.pageWithMeta?.data;
  350. if (props.isIdenticalPathPage) {
  351. // TBD
  352. }
  353. else if (page == null) {
  354. props.isNotFound = true;
  355. props.IsNotCreatable = !isCreatablePage(currentPathname);
  356. // check the page is forbidden or just does not exist.
  357. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  358. props.isForbidden = count > 0;
  359. }
  360. else {
  361. props.isNotFound = page.isEmpty;
  362. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  363. if (isPermalink && page.isEmpty) {
  364. props.currentPathname = page.path;
  365. }
  366. // /path/to/page ==> /62a88db47fed8b2d94f30000
  367. if (!isPermalink && !page.isEmpty) {
  368. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  369. if (!isToppage) {
  370. props.currentPathname = `/${page._id}`;
  371. }
  372. }
  373. }
  374. }
  375. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  376. // const req: CrowiRequest = context.req as CrowiRequest;
  377. // const { crowi } = req;
  378. // const UserModel = crowi.model('User');
  379. // if (isUserPage(props.currentPagePath)) {
  380. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  381. // if (user != null) {
  382. // props.pageUser = JSON.stringify(user.toObject());
  383. // }
  384. // }
  385. // }
  386. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  387. const req: CrowiRequest = context.req as CrowiRequest;
  388. const { crowi } = req;
  389. const {
  390. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  391. } = crowi;
  392. props.isSearchServiceConfigured = searchService.isConfigured;
  393. props.isSearchServiceReachable = searchService.isReachable;
  394. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  395. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  396. // props.isMailerSetup = mailService.isMailerSetup;
  397. props.isAclEnabled = aclService.isAclEnabled();
  398. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  399. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  400. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  401. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  402. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  403. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  404. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  405. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  406. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  407. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  408. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  409. // props.editorConfig = {
  410. // upload: {
  411. // image: crowi.fileUploadService.getIsUploadable(),
  412. // file: crowi.fileUploadService.getFileUploadEnabled(),
  413. // },
  414. // };
  415. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  416. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  417. props.rendererConfig = {
  418. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  419. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  420. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  421. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  422. plantumlUri: process.env.PLANTUML_URI ?? null,
  423. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  424. // XSS Options
  425. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  426. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  427. tagWhiteList: crowi.xssService.getTagWhiteList(),
  428. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  429. };
  430. props.sidebarConfig = {
  431. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  432. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  433. };
  434. }
  435. /**
  436. * for Server Side Translations
  437. * @param context
  438. * @param props
  439. * @param namespacesRequired
  440. */
  441. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  442. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  443. props._nextI18Next = nextI18NextConfig._nextI18Next;
  444. }
  445. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  446. const req = context.req as CrowiRequest<IUserHasId & any>;
  447. const { user } = req;
  448. const result = await getServerSideCommonProps(context);
  449. // check for presence
  450. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  451. if (!('props' in result)) {
  452. throw new Error('invalid getSSP result');
  453. }
  454. const props: Props = result.props as Props;
  455. if (user != null) {
  456. props.currentUser = user.toObject();
  457. }
  458. try {
  459. await injectPageData(context, props);
  460. }
  461. catch (err) {
  462. if (err instanceof MultiplePagesHitsError) {
  463. props.isIdenticalPathPage = true;
  464. }
  465. else {
  466. throw err;
  467. }
  468. }
  469. await injectUserUISettings(context, props);
  470. await injectRoutingInformation(context, props);
  471. injectServerConfigurations(context, props);
  472. await injectNextI18NextConfigurations(context, props, ['translation']);
  473. return {
  474. props,
  475. };
  476. };
  477. export default GrowiPage;